// 资源中台核心数据模型 - 统一建模版本

// ==================== 基础类型定义 ====================

export type ResourceId = string; // 建议 ULID/UUID
export type TenantId = string; // 多租户隔离键
export type VersionTag = string; // 语义化版本/流水号，如 "v1.2.3" / "2025.08.25.1"

// 资源基础类型 - 包含能力类型
export enum ResourceType {
  DIGITAL = 'DIGITAL', // 数字资源
  HUMAN = 'HUMAN', // 人力资源
  PHYSICAL = 'PHYSICAL', // 物理资源
  SERVICE = 'SERVICE', // 服务资源
  VIRTUAL = 'VIRTUAL', // 虚拟资源
  CAPABILITY = 'CAPABILITY', // 能力资源 - 一切皆资源，能力也是资源的一种
}

// 统一系统状态
export enum SystemStatus {
  DRAFT = 'DRAFT', // 草稿
  PUBLISHED = 'PUBLISHED', // 可被引用
  ACTIVE = 'ACTIVE', // 运行中
  INACTIVE = 'INACTIVE', // 下线但保留
  DEPRECATED = 'DEPRECATED', // 标记废弃
  RETIRED = 'RETIRED', // 退役归档
}

// 兼容旧版资源状态
export enum ResourceStatus {
  ACTIVE = 'ACTIVE', // 正常
  INACTIVE = 'INACTIVE', // 停用
  MAINTENANCE = 'MAINTENANCE', // 维护中
  AVAILABLE = 'AVAILABLE', // 可用
  OCCUPIED = 'OCCUPIED', // 占用
  OFFLINE = 'OFFLINE', // 离线
  RETIRED = 'RETIRED', // 报废
}

// ==================== 统一资源模型 ====================

/**
 * 统一资源模型 - 一切皆资源的核心接口
 */
export interface Resource {
  id: ResourceId;
  tenantId: TenantId;
  name: string;
  code?: string; // 人可读唯一码（租户内唯一）
  type: ResourceType;
  systemStatus: SystemStatus;
  version: VersionTag; // 当前生效版本
  labels?: Record<string, string>; // 轻量标签
  annotations?: Record<string, any>; // 松散注解/扩展
  facets: ResourceFacets; // 可插拔构件
  governance: Governance; // RBAC/可见性/审批等
  createdAt: string;
  updatedAt: string;
}

/**
 * 统一可插拔构件（facets）
 */
export interface ResourceFacets {
  attributes?: AttributesFacet; // 属性域（多域/多场景）
  lifecycle?: LifecycleFacet; // 状态机（系统+自定义）
  behaviors?: BehaviorsFacet; // 行为/动作链
  events?: EventsFacet; // 事件订阅/发布
  relations?: RelationsFacet; // 资源图谱关系
  capability?: CapabilityFacet; // 能力专属（仅当 type=CAPABILITY 或作为附能）
  versions?: VersionsFacet; // 历史版本/灰度/回滚
  monitoring?: MonitoringFacet; // 指标/日志/告警偏好
}

// ==================== 属性域 ====================

/**
 * 属性域管理
 */
export interface AttributesFacet {
  // 按域（domain）与场景（context）组织的属性包
  bags: AttributeBag[];
}

export interface AttributeBag {
  id: string;
  domain: 'RESOURCE' | 'ABILITY' | 'BUSINESS' | 'TECHNICAL' | 'MARKET' | string;
  context?: string; // 如 "spa.room.booking"
  schema: JSONSchema; // JSON Schema 定义（前端表单）
  values: Record<string, any>; // 按 schema 存值
  inheritsFrom?: ResourceRef[]; // 可选：继承/引用其它资源的属性包
}

export type JSONSchema = Record<string, any>;

// ==================== 生命周期/状态机 ====================

/**
 * 统一生命周期管理
 */
export interface LifecycleFacet {
  machine: StateMachine; // 统一状态机（含系统+业务）
  currentState: string; // 当前状态
  historyEnabled?: boolean;
}

export interface StateMachine {
  states: string[]; // e.g. ["IDLE","BOOKED","OCCUPIED",...]
  initial: string;
  transitions: Transition[]; // 有向边
}

export interface Transition {
  from: string;
  to: string;
  trigger: Trigger; // 触发器
  conditions?: Condition[]; // 条件
  actions?: TransitionAction[]; // 伴随动作（轻量）
}

export type Trigger =
  | { kind: 'MANUAL' }
  | { kind: 'EVENT'; eventType: string }
  | { kind: 'SCHEDULED'; cron: string }
  | { kind: 'AUTOMATIC' };

export interface Condition {
  type: 'EXPR' | 'ATTR' | 'METRIC' | 'ACL' | 'CUSTOM';
  expression?: string; // 如 CEL/SpEL
  key?: string; // ATTR/METRIC 的键
  op?: 'EQ' | 'NE' | 'GT' | 'GE' | 'LT' | 'LE' | 'IN' | 'MATCH';
  value?: any;
}

export interface TransitionAction {
  type: 'EMIT_EVENT' | 'CALL_BEHAVIOR' | 'SET_ATTR' | 'CALL_WEBHOOK';
  params?: Record<string, any>;
}

// ==================== 行为/动作 ====================

/**
 * 行为管理
 */
export interface BehaviorsFacet {
  definitions: Behavior[];
}

export interface Behavior {
  id: string;
  name: string;
  kind:
    | 'EXECUTION'
    | 'VALIDATION'
    | 'TRANSFORMATION'
    | 'NOTIFICATION'
    | 'COMPENSATION';
  inputSchema?: JSONSchema;
  outputSchema?: JSONSchema;
  steps: ActionStep[]; // 动作链
  timeoutMs?: number;
  retry?: RetryPolicy;
  boundInterfaceId?: string; // 可选：绑定对外接口
  emits?: string[]; // 行为完成时发出的事件类型
  metadata?: Record<string, any>;
}

export interface ActionStep {
  id: string;
  type:
    | 'API_CALL'
    | 'STATE_CHANGE'
    | 'EMIT_EVENT'
    | 'START_BPM'
    | 'SCRIPT'
    | 'DELAY';
  config: Record<string, any>; // 每种 type 的参数
  onError?: 'FAIL' | 'RETRY' | 'SKIP' | 'COMPENSATE';
}

export interface RetryPolicy {
  maxAttempts: number;
  backoffMs: number;
  multiplier?: number;
  maxBackoffMs?: number;
}

// ==================== 事件 ====================

/**
 * 事件管理
 */
export interface EventsFacet {
  publish?: EventBinding[]; // 本资源会发布哪些事件
  subscribe?: EventSubscription[]; // 本资源订阅什么事件
}

export interface EventBinding {
  eventType: string; // 如 "SERVICE_STARTED"
  topic?: string; // Kafka/Redis/…
  payloadSchema?: JSONSchema;
}

export interface EventSubscription {
  eventType: string;
  sourceFilter?: ResourceRef[] | TagFilter; // 订阅来源过滤
  handler: EventHandler; // 收到事件后的动作
}

export interface EventHandler {
  actions: TransitionAction[]; // 可触发状态迁移/行为/通知
}

export interface TagFilter {
  anyOf?: Record<string, string>[];
}

// ==================== 关系图谱 ====================

/**
 * 资源关系管理
 */
export interface RelationsFacet {
  edges: RelationEdge[];
}

export interface RelationEdge {
  to: ResourceRef;
  kind:
    | 'COMPOSES'
    | 'USES'
    | 'DEPENDS_ON'
    | 'DELEGATES_TO'
    | 'PROXIED_BY'
    | 'OWNED_BY';
  constraints?: Record<string, any>;
}

export interface ResourceRef {
  id: ResourceId;
  type?: ResourceType;
  name?: string; // 便于 UI 展示
}

// ==================== 能力专属 ====================

/**
 * 能力专属（作为资源的一个"面"）
 */
export interface CapabilityFacet {
  category:
    | 'BUSINESS'
    | 'TECHNICAL'
    | 'OPERATIONAL'
    | 'COMPLIANCE'
    | 'INTEGRATION'
    | string;
  definition: {
    id: string;
    code: string;
    description?: string;
  };
  specifications?: Specification[]; // 能力规格
  interfaces?: CapabilityInterface[]; // 对外接口（REST/GraphQL/gRPC/事件等）
}

export interface Specification {
  id: string;
  name: string;
  type:
    | 'FUNCTIONAL'
    | 'PERFORMANCE'
    | 'SECURITY'
    | 'INTERFACE'
    | 'DEPLOYMENT'
    | string;
  format: 'JSON' | 'YAML' | 'XML' | 'MARKDOWN' | 'TEXT';
  content: string;
  version: VersionTag;
  metadata?: Record<string, any>;
}

export interface CapabilityInterface {
  id: string;
  name: string;
  type: 'REST' | 'GRAPHQL' | 'GRPC' | 'SOAP' | 'EVENT';
  endpoint?: string; // REST/gRPC
  method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
  topic?: string; // EVENT
  inputSchema?: JSONSchema;
  outputSchema?: JSONSchema;
  auth?: {
    kind: 'NONE' | 'API_KEY' | 'BASIC' | 'BEARER' | 'OAUTH2' | 'JWT';
    scopes?: string[];
  };
  rateLimit?: {
    requests: number;
    period: string;
    burst?: number;
  };
  metadata?: Record<string, any>;
}

// ==================== 版本/灰度/回滚 ====================

/**
 * 版本管理
 */
export interface VersionsFacet {
  history: VersionRecord[];
  rollout?: RolloutPlan; // 发布/灰度策略
}

export interface VersionRecord {
  version: VersionTag;
  status: 'DRAFT' | 'RELEASED' | 'ROLLED_BACK' | 'DEPRECATED';
  changelog?: string;
  createdAt: string;
  createdBy: string;
}

export interface RolloutPlan {
  strategy: 'ALL_AT_ONCE' | 'CANARY' | 'BLUE_GREEN' | 'BATCH';
  segments?: Array<{ percentage: number; filter?: TagFilter }>;
  startAt?: string;
  freezeWindow?: { from: string; to: string };
}

// ==================== 监控与治理 ====================

/**
 * 监控管理
 */
export interface MonitoringFacet {
  metrics?: string[]; // 注册的指标键
  alerts?: AlertRule[];
  logging?: {
    level: 'DEBUG' | 'INFO' | 'WARN' | 'ERROR';
    retentionDays?: number;
  };
}

export interface AlertRule {
  id: string;
  name: string;
  severity: 'INFO' | 'WARNING' | 'ERROR' | 'CRITICAL';
  condition: string; // 表达式语言
  actions: Array<{
    type: 'WEBHOOK' | 'EMAIL' | 'SMS' | 'WORKFLOW';
    params: Record<string, any>;
  }>;
}

/**
 * 治理管理
 */
export interface Governance {
  visibility: 'PRIVATE' | 'TENANT' | 'PUBLIC';
  owners: string[]; // 责任人
  rbac?: Array<{ role: string; permissions: string[] }>;
  approvals?: Array<{ step: string; required: boolean }>;
}

// ==================== 兼容性类型定义 ====================

// 业务类型
export enum BusinessType {
  APARTMENT = 'APARTMENT', // 公寓
  HOT_SPRING = 'HOT_SPRING', // 温泉洗浴
  HOTEL = 'HOTEL', // 酒店
  MEDICAL_BEAUTY = 'MEDICAL_BEAUTY', // 医美
  OTHER = 'OTHER', // 其他
  PET_MEDICAL = 'PET_MEDICAL', // 宠物医疗
  RESTAURANT = 'RESTAURANT', // 餐饮
  TRAINING = 'TRAINING', // 培训班
}

// 资源项目类型（用于API响应）- 兼容旧版
export interface ResourceItem {
  id: string;
  name: string;
  code: string;
  resource_type: string;
  resource_sub_type?: string;
  business_type: string;
  status: string;
  description?: string;
  parent_id?: string;
  properties?: Record<string, any>;
  constraints?: Record<string, any>;
  metadata?: Record<string, any>;
  creator?: string;
  create_time: string;
  update_time: string;
  children?: ResourceItem[];
}

// 资源树节点类型
export interface ResourceTreeItem {
  key: string;
  title: string;
  children: ResourceTreeItem[];
  data?: ResourceItem;
}

// 资源分类
export interface ResourceCategory {
  id: string;
  name: string;
  type: ResourceType;
  businessTypes: BusinessType[];
  description?: string;
  metadata?: Record<string, any>;
  createdAt: string;
  updatedAt: string;
}

// 基础资源模型 - 兼容旧版
export interface BaseResource {
  id: string;
  tenantId: string;
  name: string;
  code: string;
  type: ResourceType;
  categoryId: string;
  businessTypes: BusinessType[];
  status: ResourceStatus;
  location?: string;
  capacity?: number;
  unit?: string;
  price?: number;
  currency?: string;
  tags: string[];
  metadata: Record<string, any>;
  createdAt: string;
  updatedAt: string;
}

// 物理资源
export interface PhysicalResource extends BaseResource {
  type: ResourceType.PHYSICAL;
  specifications?: string;
  manufacturer?: string;
  model?: string;
  purchaseDate?: string;
  warrantyExpiry?: string;
  maintenanceCycle?: number; // 维护周期(天)
  lastMaintenance?: string;
  nextMaintenance?: string;
  depreciationRate?: number; // 折旧率
  currentValue?: number; // 当前价值
}

// 人力资源
export interface HumanResource extends BaseResource {
  type: ResourceType.HUMAN;
  employeeId?: string;
  position?: string;
  department?: string;
  skills: string[];
  experience?: number; // 工作经验(年)
  hourlyRate?: number;
  availability: ResourceAvailability[];
  qualifications?: string[];
  certifications?: string[];
}

// 数字资源
export interface DigitalResource extends BaseResource {
  type: ResourceType.DIGITAL;
  url?: string;
  fileSize?: number;
  fileType?: string;
  version?: string;
  license?: string;
  expiryDate?: string;
  accessLevel?: string;
  storageLocation?: string;
}

// 服务资源
export interface ServiceResource extends BaseResource {
  type: ResourceType.SERVICE;
  serviceType?: string;
  duration?: number; // 服务时长(分钟)
  maxConcurrent?: number; // 最大并发数
  prerequisites?: string[];
  dependencies?: string[];
  qualityLevel?: string;
  sla?: string; // 服务级别协议
}

// 能力资源 - 新的统一模型
export interface CapabilityResource extends BaseResource {
  type: ResourceType.CAPABILITY;
  // 使用新的统一模型
  facets: ResourceFacets;
  governance: Governance;
}

// ==================== 资源可用性 ====================

// 资源可用性
export interface ResourceAvailability {
  id: string;
  resourceId: string;
  dayOfWeek: number; // 0-6 (周日-周六)
  startTime: string; // HH:mm
  endTime: string; // HH:mm
  isAvailable: boolean;
  maxBookings?: number;
  currentBookings?: number;
}

// 资源调度
export interface ResourceSchedule {
  id: string;
  resourceId: string;
  tenantId: string;
  businessType: BusinessType;
  startTime: string;
  endTime: string;
  status: ScheduleStatus;
  bookingId?: string;
  customerId?: string;
  notes?: string;
  createdAt: string;
  updatedAt: string;
}

// 调度状态
export enum ScheduleStatus {
  CANCELLED = 'CANCELLED', // 已取消
  COMPLETED = 'COMPLETED', // 已完成
  CONFIRMED = 'CONFIRMED', // 已确认
  IN_PROGRESS = 'IN_PROGRESS', // 进行中
  PENDING = 'PENDING', // 待确认
}

// 资源使用记录
export interface ResourceUsage {
  id: string;
  resourceId: string;
  tenantId: string;
  businessType: BusinessType;
  startTime: string;
  endTime: string;
  duration: number; // 使用时长(分钟)
  usageType: UsageType;
  customerId?: string;
  bookingId?: string;
  cost?: number;
  revenue?: number;
  rating?: number;
  feedback?: string;
  createdAt: string;
}

// 使用类型
export enum UsageType {
  BOOKING = 'BOOKING', // 预约使用
  MAINTENANCE = 'MAINTENANCE', // 维护使用
  TESTING = 'TESTING', // 测试使用
  WALK_IN = 'WALK_IN', // 现场使用
}

// 资源维护记录
export interface ResourceMaintenance {
  id: string;
  resourceId: string;
  type: MaintenanceType;
  description: string;
  startTime: string;
  endTime?: string;
  cost?: number;
  technician?: string;
  parts?: string[];
  status: MaintenanceStatus;
  notes?: string;
  createdAt: string;
  updatedAt: string;
}

// 维护类型
export enum MaintenanceType {
  CORRECTIVE = 'CORRECTIVE', // 纠正性维护
  EMERGENCY = 'EMERGENCY', // 紧急维护
  PREVENTIVE = 'PREVENTIVE', // 预防性维护
  UPGRADE = 'UPGRADE', // 升级维护
}

// 维护状态
export enum MaintenanceStatus {
  CANCELLED = 'CANCELLED', // 已取消
  COMPLETED = 'COMPLETED', // 已完成
  IN_PROGRESS = 'IN_PROGRESS', // 进行中
  PLANNED = 'PLANNED', // 计划中
}

// 资源采购
export interface ResourcePurchase {
  id: string;
  tenantId: string;
  resourceName: string;
  resourceType: ResourceType;
  categoryId: string;
  quantity: number;
  unitPrice: number;
  totalAmount: number;
  supplier: string;
  purchaseDate: string;
  expectedDelivery?: string;
  actualDelivery?: string;
  status: PurchaseStatus;
  notes?: string;
  createdAt: string;
  updatedAt: string;
}

// 采购状态
export enum PurchaseStatus {
  APPROVED = 'APPROVED', // 已批准
  CANCELLED = 'CANCELLED', // 已取消
  DELIVERED = 'DELIVERED', // 已交付
  DRAFT = 'DRAFT', // 草稿
  ORDERED = 'ORDERED', // 已下单
  RECEIVED = 'RECEIVED', // 已接收
  SUBMITTED = 'SUBMITTED', // 已提交
}

// 跨业态资源共享配置
export interface CrossBusinessSharing {
  id: string;
  resourceId: string;
  sourceBusinessType: BusinessType;
  targetBusinessTypes: BusinessType[];
  sharingType: SharingType;
  priority: number;
  costAllocation: CostAllocation;
  isActive: boolean;
  startDate?: string;
  endDate?: string;
  createdAt: string;
  updatedAt: string;
}

// 共享类型
export enum SharingType {
  EXCLUSIVE = 'EXCLUSIVE', // 独占
  ON_DEMAND = 'ON_DEMAND', // 按需
  ROTATING = 'ROTATING', // 轮换
  SHARED = 'SHARED', // 共享
}

// 成本分配
export interface CostAllocation {
  method: AllocationMethod;
  percentage?: number;
  fixedAmount?: number;
  formula?: string;
}

// 分配方法
export enum AllocationMethod {
  EQUAL = 'EQUAL', // 平均分配
  FIXED = 'FIXED', // 固定金额
  FORMULA = 'FORMULA', // 公式计算
  PERCENTAGE = 'PERCENTAGE', // 按比例
  USAGE_BASED = 'USAGE_BASED', // 按使用量
}

// ==================== 多领域属性管理类型定义 ====================

// 领域枚举
export enum PropertyDomain {
  BUSINESS = 'BUSINESS', // 业务领域
  COMPLIANCE = 'COMPLIANCE', // 合规风控
  OPERATION = 'OPERATION', // 运营领域
  TECHNICAL = 'TECHNICAL', // 技术领域
}

// 领域配置
export interface DomainConfig {
  key: PropertyDomain;
  name: string;
  description: string;
  icon: string;
  color: string;
  visible: boolean;
  editable: boolean;
  required: boolean;
  order: number;
}

// 字段组件类型
export enum FieldComponent {
  CASCADER = 'Cascader',
  CHECKBOX_GROUP = 'CheckboxGroup',
  DATE_PICKER = 'DatePicker',
  INPUT = 'Input',
  INPUT_NUMBER = 'InputNumber',
  RADIO_GROUP = 'RadioGroup',
  SELECT = 'Select',
  SWITCH = 'Switch',
  TEXTAREA = 'Textarea',
  UPLOAD = 'Upload',
}

// 字段验证规则
export interface FieldValidation {
  required?: boolean;
  minLength?: number;
  maxLength?: number;
  minValue?: number;
  maxValue?: number;
  pattern?: string;
  customRule?: string;
  message?: string;
}

// 字段Schema
export interface FieldSchema {
  id: string;
  fieldName: string;
  label: string;
  component: FieldComponent;
  componentProps: Record<string, any>;
  rules?: string | string[];
  defaultValue?: any;
  domain: PropertyDomain;
  dependencies?: string[];
  permissions?: string[];
  order: number;
  isActive: boolean;
  description?: string;
  validation?: FieldValidation;
  metadata?: Record<string, any>;
}

// 领域属性数据
export interface DomainProperties {
  schema: FieldSchema[];
  data: Record<string, any>;
  config: DomainConfig;
  metadata?: {
    lastModified: string;
    modifiedBy: string;
    version: string;
  };
}

// 多领域属性结构
export interface MultiDomainProperties {
  domains: Record<PropertyDomain, DomainProperties>;
  metadata: {
    domainCount: number;
    lastModified: string;
    modifiedBy: string;
    totalFields: number;
    version: string;
  };
}

// API 请求参数
export interface ResourceQueryParams {
  pageNo?: number;
  pageSize?: number;
  type?: ResourceType;
  categoryId?: string;
  businessTypes?: BusinessType[];
  status?: ResourceStatus;
  keyword?: string;
  tags?: string[];
  startDate?: string;
  endDate?: string;
}

export interface ScheduleQueryParams {
  pageNo?: number;
  pageSize?: number;
  resourceId?: string;
  businessType?: BusinessType;
  status?: ScheduleStatus;
  startDate?: string;
  endDate?: string;
}

// API 响应
export interface ResourceListResponse {
  list: BaseResource[];
  total: number;
  pageNo: number;
  pageSize: number;
}

export interface ScheduleListResponse {
  list: ResourceSchedule[];
  total: number;
  pageNo: number;
  pageSize: number;
}

export interface ResourceOverviewResponse {
  totalResources: number;
  onlineResources: number;
  utilizationRate: number;
  todaySchedules: number;
  byType: Record<ResourceType, number>;
  byBusinessType: Record<BusinessType, number>;
  byStatus: Record<ResourceStatus, number>;
}

// 占用记录列表响应
export interface OccupancyListResponse {
  items: ResourceUsage[];
  total: number;
}

// 分析趋势响应
export interface AnalyticsTrendsResponse {
  occupancyTrend: Array<{ date: string; value: number }>;
  costAnalysis: Array<{ category: string; value: number; percentage: number }>;
  utilizationByType: Array<{ type: string; value: number }>;
  efficiencyTrend: Array<{ date: string; value: number }>;
  faultAnalysis: Array<{ type: string; count: number; percentage: number }>;
}

// API 请求参数
export interface PropertyQueryParams {
  resourceId: string;
  domain?: PropertyDomain;
  includeInactive?: boolean;
}

export interface PropertyUpdateParams {
  resourceId: string;
  domain: PropertyDomain;
  properties: DomainProperties;
}

// API 响应
export interface PropertyResponse {
  success: boolean;
  data: MultiDomainProperties;
  message?: string;
}

export interface DomainPropertyResponse {
  success: boolean;
  data: DomainProperties;
  message?: string;
}

// 字段模板
export interface FieldTemplate {
  id: string;
  name: string;
  description: string;
  domain: PropertyDomain;
  template: Partial<FieldSchema>;
  isSystem: boolean;
  usageCount: number;
  createdAt: string;
  updatedAt: string;
}

// 领域模板
export interface DomainTemplate {
  id: string;
  name: string;
  description: string;
  domain: PropertyDomain;
  fields: FieldTemplate[];
  isSystem: boolean;
  usageCount: number;
  createdAt: string;
  updatedAt: string;
}
